package wsi.dataguide;

import java.util.Map.Entry;
import java.util.Stack;

import org.rygh.semantic.gui.swing.input.Input;

import wsi.dataguide.tree.WSXmlLeaf;
import wsi.dataguide.tree.WSXmlObject;
import wsi.dataguide.tree.WSXmlParser;
import wsi.dataguide.tree.WSXmlTree;

public class DataGuideParser extends WSXmlParser {

	private final DataGuide dataGuide;
	private final Stack<WSXmlLeaf> stack = new Stack<>();

	public DataGuideParser(Input input, String xml, DataGuide dataGuide) {
		super(input, xml, true);

		assert !xml.isEmpty();
		this.dataGuide = dataGuide;
	}

	@Override
	public WSXmlTree parse() {
		super.parse();

		// System.out.println(referenceTree);

		stack.clear();
		stack.push(dataGuide.getRoot());

		for (Entry<String, String> e : xmlTree.getPrefixMap().entrySet())
			dataGuide.addPrefix(e.getKey(), e.getValue());

		parse2(xmlTree.getConcreteRoot());

		return xmlTree;
	}

	private void parse2(WSXmlLeaf nodeInXml) {

		WSXmlObject obj = nodeInXml.getValue();
		WSXmlLeaf node = null;

		WSXmlLeaf parent = stack.peek();

		if (parent.isLeaf()) {
			node = new WSXmlLeaf(parent, obj);
		} else {

			WSXmlLeaf _node = null;

			for (WSXmlLeaf i : parent.getChildren()) {
				WSXmlLeaf _i = i;
				WSXmlObject _n = _i.getValue();

				if (_n.getName().equals(obj.getName())) {
					_node = _i;
					break;
				}
			}

			if (_node == null) {
				node = new WSXmlLeaf(parent, obj);
			} else {
				node = _node;
				// node.getObject().addValues(name, obj.getValueSet());
				node.getValue().addValues(input, obj.getValueMap().get(input));
			}

		}

		assert node != null;
		stack.push(node);
		dataGuide.count(node, nodeInXml);

		if (!nodeInXml.isLeaf())
			for (WSXmlLeaf i : nodeInXml.getChildren())
				parse2(i);

		stack.pop();
	}

}
